import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/vpn_provider.dart';
import '../widgets/server_list.dart';
import '../widgets/server_import_dialog.dart';
import '../widgets/batch_ping_test_dialog.dart';
import '../utils/theme.dart';
import '../l10n/app_localizations.dart';

class ServersScreen extends StatefulWidget {
  const ServersScreen({super.key});

  @override
  State<ServersScreen> createState() => _ServersScreenState();
}

class _ServersScreenState extends State<ServersScreen> {
  final TextEditingController _searchController = TextEditingController();

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.navServers),
        actions: [
          IconButton(
            icon: const Icon(Icons.speed),
            onPressed: () {
              final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
              final serversToTest = vpnProvider.servers.toList();
              
              if (serversToTest.isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Row(
                      children: [
                        Icon(Icons.info_outline, color: Colors.white),
                        SizedBox(width: 12),
                        Text('No servers to test'),
                      ],
                    ),
                    backgroundColor: Colors.blue,
                  ),
                );
                return;
              }
              
              // 显示批量测速对话框
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) => BatchPingTestDialog(
                  servers: serversToTest,
                ),
              );
            },
            tooltip: l10n.translate('server_test_all'),
          ),
          IconButton(
            icon: const Icon(Icons.sort),
            onPressed: () {
              _showSortOptions(context, l10n);
            },
            tooltip: 'Sort',
          ),
        ],
      ),
      body: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Theme.of(context).brightness == Brightness.dark
                  ? Colors.grey.shade900.withOpacity(0.5)
                  : Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              children: [
                // Search bar
                TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText: l10n.translate('server_search'),
                    prefixIcon: const Icon(Icons.search),
                    suffixIcon: _searchController.text.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear),
                            onPressed: () {
                              setState(() {
                                _searchController.clear();
                                Provider.of<VpnProvider>(context, listen: false)
                                    .setSearchQuery('');
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    filled: true,
                    fillColor: Theme.of(context).brightness == Brightness.dark
                        ? Colors.grey.shade800.withOpacity(0.5)
                        : Colors.grey.shade50,
                  ),
                  onChanged: (value) {
                    setState(() {});
                    Provider.of<VpnProvider>(context, listen: false)
                        .setSearchQuery(value);
                  },
                ),
                const SizedBox(height: 16),
                
                // Filter chips
                Consumer<VpnProvider>(
                  builder: (context, vpnProvider, _) {
                    return SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          Chip(
                            avatar: const Icon(Icons.list, size: 18),
                            label: Text('All (${vpnProvider.servers.length})'),
                            backgroundColor: Theme.of(context).brightness == Brightness.dark
                                ? Colors.grey.shade800.withOpacity(0.5)
                                : Colors.grey.shade100,
                          ),
                          const SizedBox(width: 8),
                          FilterChip(
                            label: Text(l10n.translate('server_favorites')),
                            selected: vpnProvider.showFavoritesOnly,
                            onSelected: (selected) {
                              vpnProvider.toggleFavoritesOnly();
                            },
                            avatar: Icon(
                              Icons.star,
                              size: 18,
                              color: vpnProvider.showFavoritesOnly
                                  ? Colors.white
                                  : AppTheme.primaryColor,
                            ),
                            selectedColor: AppTheme.primaryColor,
                            checkmarkColor: Colors.white,
                          ),
                          const SizedBox(width: 8),
                          ...vpnProvider.groups.map((group) {
                            final isSelected = vpnProvider.selectedGroup == group;
                            return Padding(
                              padding: const EdgeInsets.only(right: 8),
                              child: FilterChip(
                                label: Text(group),
                                selected: isSelected,
                                onSelected: (selected) {
                                  if (selected) {
                                    vpnProvider.setSelectedGroup(group);
                                  } else {
                                    vpnProvider.setSelectedGroup('All');
                                  }
                                },
                                selectedColor: AppTheme.secondaryColor,
                                checkmarkColor: Colors.white,
                              ),
                            );
                          }),
                        ],
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
          
          // Server list
          Expanded(
            child: Consumer<VpnProvider>(
              builder: (context, vpnProvider, _) {
                if (vpnProvider.servers.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.dns_outlined,
                          size: 80,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.grey.shade700
                              : Colors.grey.shade300,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          l10n.translate('msg_no_servers'),
                          style: TextStyle(
                            fontSize: 16,
                            color: Theme.of(context).brightness == Brightness.dark
                                ? Colors.grey.shade400
                                : Colors.grey.shade600,
                          ),
                        ),
                        const SizedBox(height: 24),
                        ElevatedButton.icon(
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (context) => const ServerImportDialog(),
                            );
                          },
                          icon: const Icon(Icons.add),
                          label: Text(l10n.translate('server_add')),
                        ),
                      ],
                    ),
                  );
                }
                
                // 显示分组标签（当不是在筛选特定分组时）
                final showGroupBadge = vpnProvider.selectedGroup == 'All';
                return ServerList(showGroupBadge: showGroupBadge);
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) => const ServerImportDialog(),
          );
        },
        icon: const Icon(Icons.add),
        label: Text(l10n.translate('server_add')),
      ),
    );
  }

  void _showSortOptions(BuildContext context, AppLocalizations l10n) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    final currentSortMode = vpnProvider.sortMode;
    
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.grey.shade600
                    : Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              'Sort By',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 20),
            ListTile(
              leading: const Icon(Icons.access_time),
              title: const Text('Recent'),
              trailing: currentSortMode == ServerSortMode.recent 
                  ? const Icon(Icons.check, color: AppTheme.primaryColor) 
                  : null,
              onTap: () {
                vpnProvider.setSortMode(ServerSortMode.recent);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.speed),
              title: const Text('Ping'),
              trailing: currentSortMode == ServerSortMode.ping 
                  ? const Icon(Icons.check, color: AppTheme.primaryColor) 
                  : null,
              onTap: () {
                vpnProvider.setSortMode(ServerSortMode.ping);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.sort_by_alpha),
              title: const Text('Name'),
              trailing: currentSortMode == ServerSortMode.name 
                  ? const Icon(Icons.check, color: AppTheme.primaryColor) 
                  : null,
              onTap: () {
                vpnProvider.setSortMode(ServerSortMode.name);
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}
